/**
 * 
 */
package pt.xpand.xinx.entities;

import pt.xpand.xinx.entities.interfaces.IPlayer;

/**
 * @author Kiko
 * 
 */
public class Bracket {

	private IPlayer	player1;
	private IPlayer	player2;
	private IPlayer	winner;

	private int		score1;
	private int		score2;

	private int		gamesPlayed;

	private int		bestOf;

	public Bracket(IPlayer p1, IPlayer p2, int bestOf) {
		this.player1 = p1;
		this.player2 = p2;
		this.score1 = 0;
		this.score2 = 0;
		this.bestOf = bestOf;
		this.gamesPlayed = 0;
		if (player2 == null) {
			score1 = bestOf;
			this.gamesPlayed = bestOf;
			this.winner = player1;
		}
	}

	/**
	 * @return the player1
	 */
	public IPlayer getPlayer1() {
		return player1;
	}

	/**
	 * @return the player2
	 */
	public IPlayer getPlayer2() {
		return player2;
	}

	/**
	 * @return the score1
	 */
	public int getScore1() {
		return score1;
	}

	public void addVictory(IPlayer p) {
		// TODO: validar casos de empate
		if (p != null) {
			if (p.getName().equals(player1.getName())) {
				score1++;
				if (score1 > bestOf / 2) {
					winner = player1;
					System.out.println("Bracket terminated: Winner is " + winner.getName());
					gamesPlayed++;
					return;
				}
			} else {
				score2++;
				if (score2 > bestOf / 2) {
					winner = player2;
					System.out.println("Bracket terminated: Winner is " + winner.getName());
					gamesPlayed++;
					return;
				}
			}
		}

		//gamesPlayed++;
		if (gamesPlayed == bestOf) {
			if (score1 > score2) {
				winner = player1;
			} else {
				winner = player2;
			}
			System.out.println("Bracket terminated: Winner is " + winner.getName());
		}
	}

	/**
	 * @return the score2
	 */
	public int getScore2() {
		return score2;
	}

	/**
	 * @return the bestOf
	 */
	public int getBestOf() {
		return bestOf;
	}

	/**
	 * @return
	 */
	public int getGamesPlayed() {
		return gamesPlayed;
	}

	public IPlayer getWinner() {
		return winner;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuffer t = new StringBuffer(player1.getName() + " - " + score1 + " \n");
		if(player2 != null) {
			t.append(player2.getName() + " - " + score2 + "\n");
		}
		return t.toString();
	}

}
